const regeneratorRuntime = require("../../utils/runtime.js")

function randomStr(len) {　　
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ 　　
  var maxPos = $chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {　　　　
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }　　
  return pwd
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputing: false,
    msgList: [],
    listDic: [],
    // list: [{
    //     id: 0,
    //     type: 'content',
    //     content: '你好呀',
    //     autoplay: false,
    //     options: [{
    //         text: 'JavaScript',
    //         goto: 1
    //       },
    //       {
    //         text: 'HTML5',
    //         goto: 2
    //       },
    //       {
    //         text: 'CSS3',
    //         goto: 2
    //       }
    //     ]
    //   },
    //   {
    //     id: 1,
    //     type: 'content',
    //     content: `暂时没有 JS 试题哦`,
    //     autoplay: false,
    //     self: false
    //   },

    //   {
    //     id: 2,
    //     type: 'code',
    //     content: `const a = 1\na = 2\nconsole.log(a)`,
    //     autoplay: {
    //       timeout: 5000,
    //       goto: 'next'
    //     }
    //   },

    //   {
    //     id: 3,
    //     type: 'content',
    //     content: `下面代码输出什么呢？ =u=`,
    //     autoplay: {
    //       timeout: 1000,
    //       goto: 'next'
    //     },
    //   },

    //   {
    //     id: 4,
    //     type: 'image',
    //     content: `https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2417759118,4118045502&fm=26&gp=0.jpg`,
    //     autoplay: false
    //   },
    // ]
    list: [{
        "type": "content",
        "content": "事件循环、宏任务、微任务练习题",
        "autoplay": {
          "goto": "next",
          "timeout": "1000"
        },
        "options": [],
        "id": "test_15813574441275"
      },
      {
        "type": "content",
        "content": "Event loop （事件循环）是一个执行模型，在不同的地方有不同的实现。浏览器和 NodeJS 基于不同的技术实现了各自的 Event Loop。",
        "autoplay": {
          "goto": "next",
          "timeout": "5000"
        },
        "options": [],
        "id": "test_15813590451326"
      },
      {
        "type": "content",
        "content": "由于这个模型的存在，Node.js 拥有了单线程高效的异步 I/O 模型，被广泛应用于服务端中处理那些需要高并发的场景中。",
        "autoplay": {
          "goto": "next",
          "timeout": "3000"
        },
        "options": [],
        "id": "test_15813590810820"
      },
      {
        "type": "content",
        "content": "还需要了解哪些信息？",
        "autoplay": {},
        "options": [{
          "text": "宏任务、微任务",
          "goto": "test_158135916774145",
          "key": 0
        }],
        "id": "test_15813591017745"
      },
      {
        "type": "content",
        "content": "宏任务，微任务的介绍～",
        "autoplay": {
          "goto": "next",
          "timeout": "1000"
        },
        "options": [],
        "id": "test_158135916774145"
      },
      {
        "type": "content",
        "content": "以下任务都是宏任务哦～",
        "autoplay": {
          "goto": "next",
          "timeout": "500"
        },
        "options": [],
        "id": "test_158135922725747"
      },
      {
        "type": "content",
        "content": "【宏任务】\n（1）setTimeout，setInterval，setImmediate\n（2）整体代码（浏览器中的 <script> 标签，Node 中全局作用域下的代码）",
        "autoplay": {
          "goto": "next",
          "timeout": "2000"
        },
        "options": [],
        "id": "test_158135925041292"
      },
      {
        "type": "content",
        "content": "以下是微任务～",
        "autoplay": {
          "goto": "next",
          "timeout": "1000"
        },
        "options": [{
          "text": "",
          "goto": "",
          "key": 0
        }],
        "id": "test_158135929330855"
      },
      {
        "type": "content",
        "content": "【微任务】\n（1）异步回调 promise.then(fn)\n（2）Node 特有的 process.nextTick(fn)\n（3）IE 全家桶才支持的 setImmediate(fn)",
        "autoplay": {
          "goto": "next",
          "timeout": "6000"
        },
        "options": [],
        "id": "test_158135931493577"
      },
      {
        "type": "content",
        "content": "准备好了吗？马上要开始答题啦！",
        "autoplay": {
          "goto": "next",
          "timeout": 0
        },
        "options": [{
          "text": "准备好了",
          "goto": "test_158135944602169",
          "key": 0
        }],
        "id": "test_158135938749562"
      },
      {
        "type": "code",
        "content": "console.log(1)\n\nsetTimeout(() => {\n  console.log(2)\n  Promise.resolve().then(() => {\n    console.log(3)\n  })\n})\n\nnew Promise((resolve, reject) => {\n  console.log(4)\n  resolve(5)\n}).then(data => {\n  console.log(data)\n})\n\nsetTimeout(() => {\n  console.log(6)\n})\n\nconsole.log(7)",
        "autoplay": {
          "goto": "next",
          "timeout": "7000"
        },
        "options": [],
        "id": "test_158135944602169"
      },
      {
        "type": "content",
        "content": "以上代码的输出结果是？",
        "autoplay": {},
        "options": [{
            "text": "1345726",
            "goto": "test_158135970847198",
            "key": 0
          },
          {
            "text": "1372456",
            "goto": "test_158135970847198",
            "key": 1
          },
          {
            "text": "1475236",
            "goto": "test_158135981025918",
            "key": 2
          },
          {
            "text": "1475326",
            "goto": "test_158135970847198",
            "key": 3
          }
        ],
        "id": "test_158135966518715"
      },
      {
        "type": "image",
        "content": "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3103489792,1717682834&fm=26&gp=0.jpg",
        "autoplay": {
          "goto": "test_158135966518715",
          "timeout": "1000"
        },
        "options": [],
        "id": "test_158135970847198"
      },
      {
        "type": "content",
        "content": "回答正确！～",
        "autoplay": {},
        "options": [],
        "id": "test_158135981025918"
      }
    ]
  },

  onLoad() {
    this.setData({
      listDic: this.makeDic(this.data.list)
    })

    this.showFirstMessage()
  },

  handleGotSend(e) {
    let list = this.data.list,
      msgList = this.data.msgList
    let key = new Date().valueOf(),
      item = {
        id: key,
        type: 'content',
        content: e.detail.value || ' ',
        autoplay: {
          timeout: 3000,
          goto: 'next'
        },
        self: true
      }
    list.push(item)
    item.pid = randomStr()
    msgList.push(item)

    this.setData({
      list,
      listDic: this.makeDic(list),
      msgList
    })

    wx.pageScrollTo({
      selector: '#c_' + item.pid
    })

  },

  makeDic(list = []) {
    let arr = []
    list.forEach(item => {
      if (item.id !== undefined) {
        arr.push(item.id)
      }
    })
    return arr
  },

  handleMsgSelected(e) {
    if (e.detail.info) {
      this.showMessage(e.detail.info)
    }
  },

  showFirstMessage() {
    let list = this.data.list,
      msgList = this.data.msgList,
      listDic = this.data.listDic

    if (msgList.length === 0 && list.length > 0) {
      let info = list[0]
      info.pid = randomStr()
      msgList.push(info)
      this.setData({
        msgList
      })

      wx.pageScrollTo({
        selector: '#bottom_'
      })

      this.showMessage()
    }
  },

  async showMessage(info) {
    let list = this.data.list,
      msgList = this.data.msgList,
      listDic = this.data.listDic,
      key = new Date().valueOf()
    if (!info || !info.goto || !info.text) {
      /* 如果没有 info，那就照常检查 msgList 末尾是否能自动播放下一条 */
      let now = msgList[msgList.length - 1]
      if (now && now.autoplay && now.autoplay.timeout && now.autoplay.goto) {
        let automsg, timeout
        if (now.autoplay.goto !== 'next') {
          automsg = list[listDic.indexOf(now.autoplay.goto)] || {
            id: key,
            type: 'content',
            content: `没有找到自动播放消息`,
            self: false
          }
          timeout = now.autoplay.timeout || 0
        } else {
          automsg = list[listDic.indexOf(now.id) * 1 + 1]
          if (!automsg) return
          timeout = automsg.autoplay.timeout || 0
        }

        if (automsg.self) return // 屏蔽右侧（用户）消息

        automsg.pid = randomStr()
        this.setData({
          inputing: true
        })
        await this.sleep(() => {
          msgList.push(automsg)
          this.setData({
            msgList,
            inputing: false
          })
          wx.pageScrollTo({
            selector: '#bottom_'
          })
          this.showMessage()

        }, timeout)
      }
    } else {
      /* 如果有给 info，那就跳转显示 msg */

      // 根据 info 的 goto 反查 listDic，以确定 list 中的对象位置
      let msg = list[listDic.lastIndexOf(info.goto)] || {
        id: key,
        type: 'content',
        content: `没有找到相关消息`,
        self: false
      }

      msg.pid = randomStr()

      let mymsg = {
        id: key,
        pid: randomStr(),
        type: 'content',
        content: info.text,
        autoplay: {
          timeout: 3000,
          goto: 'next'
        },
        self: true
      }
      msgList.push(mymsg)

      this.setData({
        msgList,
        inputing: true,
      })

      wx.pageScrollTo({
        selector: '#c_' + mymsg.pid
      })

      await this.sleep(() => {
        msgList.push(msg)
        this.setData({
          msgList,
          inputing: false,
        })
        wx.pageScrollTo({
          selector: '#bottom_'
        })
        this.showMessage()

      }, 500)
    }
  },

  async sleep(fn, timeout) {
    console.log(timeout)
    const wait = () => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(true)
        }, timeout)
      })
    }

    await wait()
    fn()
  }

})